import { onMounted, onUnmounted, ref } from 'vue'
export default function useKeyboardMove(x, y, speed) {
  const moveX = ref(x)
  const moveY = ref(y)
  let timer
  const commandList = []

  const commandUp = {
    type: 'upAndDown',
    dir: -1,
    id: 1
  }
  const commandDown = {
    type: 'upAndDown',
    dir: 1,
    id: 2
  }
  const commandLeft = {
    type: 'leftAndRight',
    dir: -1,
    id: 3
  }
  const commandRight = {
    type: 'leftAndRight',
    dir: 1,
    id: 4
  }

  const commandMap = {
    ArrowUp: commandUp,
    ArrowDown: commandDown,
    ArrowLeft: commandLeft,
    ArrowRight: commandRight
  }




  function handleKeydown(e) {
    let command = commandMap[e.code]
    if (command && !commandList.includes(command)) {
      commandList.unshift(command)
    }
  }

  function handleKeyup(e) {
    if (commandMap[e.code]) {
      let command = commandMap[e.code]
      let index = commandList.findIndex((item) => {
        return item.id === command.id
      })
      commandList.splice(index, 1)
    }
  }


  onMounted(() => {
    timer = setInterval(() => {
      if (moveX.value < 0) {
        moveX.value = 0
      }
      if (moveX.value > 375 * 0.8) {
        moveX.value = 375 * 0.8
      }
      if (moveY.value < 0) {
        moveY.value = 0
      }
      if (moveY.value > 540 * 0.8) {
        moveY.value = 540 * 0.8
      }
      let command1 = commandList.find((item) => {
        return item.type === 'upAndDown'
      })
      if (command1) {
        moveY.value += command1.dir * speed
      }
      let command2 = commandList.find((item) => {
        return item.type === 'leftAndRight'
      })
      if (command2) {
        moveX.value += command2.dir * speed
      }
    }, 14)
    window.addEventListener('keydown', handleKeydown)
    window.addEventListener('keyup', handleKeyup)
  })


  onUnmounted(() => {
    clearInterval(timer)
    timer = null
    window.removeEventListener('keydown', handleKeydown)
    window.removeEventListener('keyup', handleKeyup)
  })

  return { moveX, moveY }
}